<?php
namespace Model;

use Core\Constant;
use Core\Exception\BusinessException;
use Core\Helper\CommonHelper;
use Core\Session\AdminSessionHelper;
use Model\Factory\TableGatewayFactory;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Predicate\Like;
use Zend\Db\Sql\Predicate\Operator;
use Zend\Db\Sql\Select;
use Zend\InputFilter\InputFilter;

class DishTable extends AbstractTable implements LanguageAwareInterface
{
    private $_lang;

    /**
     * @param $id
     * @return Dish
     */
    public function getDish($id){
        return $this->getById($id);
    }

    /**
     * @param $name
     * @return Dish
     */
    public function getDishByName($name)
    {
        return $this->getByColumn('name', $name)->current();
    }

    /**
     * @return InputFilter
     */
    public function getInputFilter()
    {
        $filter = new InputFilter();


        return $filter;
    }

    public function search($isPaging, $offset, $rowPerPage, $orderArr = array('name'), $searchOption){

        $select = $this->getDbSqlSelect();
        $select->join(array('dl'=>'dish_lang'), 'dish.id = dl.dish_id',
            array('name'=>'name', 'description'=>'description'))
            ->where(array('dl.lang'=>AdminSessionHelper::getCurrentLang()));

        if($searchOption['name']){
            $select->where(array('dl.name like "%'.$searchOption['name'].'%"'));
        }

        if($searchOption['category'] && $searchOption['category'] != Constant::$SELECT_ALL_VALUE){
            $select->join(array('dc'=>'dish_category'), 'dc.dish_id = dish.id', array())
                ->where(array('dc.category_id'=>$searchOption['category']));
        }


        if($isPaging){
            $select->offset($offset)->limit($rowPerPage);
        }

        if($orderArr){
            $select->order($orderArr);
        }

//        \Logger::debug($select->getSqlString($this->tableGateway->adapter->getPlatform()));

        $rows = $this->tableGateway->selectWith($select);
        $result['rows'] = $rows;

        $total = $this->getCount($select);

        $result['total'] = $total;

        return $result;


    }

    public function getLang()
    {
        return $this->_lang;
    }

    public function setLang($lang)
    {
        $this->_lang = $lang;
    }


    public function addDish($paramArr){

        $name = $paramArr['name'];
        $description = $paramArr['description'];
        $active = $paramArr['active'];
        $allTag = $paramArr['allTag'];
        $content = $paramArr['content'];
        $ingredient = $paramArr['ingredient'];
        $howTo = $paramArr['howTo'];
        $mainCategories = $paramArr['mainCategories'];
        $subCategories = $paramArr['subCategories'];
        $priceArr = $paramArr['priceArr'];
        $properties = $paramArr['properties'];
        $articleArr = $paramArr['articleArr'];
        $allImages = $paramArr['allImages'];


        if(strlen($name) == 0)
            throw new BusinessException('Chưa nhập tên');
        if(strlen($description) == 0)
            throw new BusinessException('Chưa nhập mô tả');

        $propertiesAsString =  '';
        if( count($properties) > 0)
            $propertiesAsString = implode(Constant::$SYSTEM_DELIMINATOR, $properties);

            $dishId = $this->insert(array('property' => $propertiesAsString, 'active'=>$active));

            $dishLangTable = TableGatewayFactory::getDishLangTable($this->getLang());
            $dishLangTable->insert(array('dish_id'=>$dishId, 'content'=>$content,
                'alias'=>CommonHelper::vietnameseToASCII($name),
                'how_to'=>$howTo, 'ingredient'=>$ingredient, 'name'=>$name,
                'description'=>$description));

            $dishCategoryTable = TableGatewayFactory::getDishCategoryTable();
            if($mainCategories)
                foreach ($mainCategories as $aCategory) {
                    if($aCategory->lang == $this->lang)
                        $dishCategoryTable->insert(array('dish_id'=>$dishId,
                            'category_id'=>$aCategory));
                }
            if($subCategories)
                foreach ($subCategories as $aCategory) {
                    if($aCategory->lang == $this->lang)
                        $dishCategoryTable->insert(array('dish_id'=>$dishId,
                            'category_id'=>$aCategory));
                }

            $dishTagTable = TableGatewayFactory::getDishTagTable($this->getLang());
            if($allTag)
                foreach ($allTag as $aTag) {
                    $dishTagTable->insert(array('dish_id'=>$dishId, 'tag'=>$aTag));
                }

        throw new BusinessException('mama calls me');

            $dishPriceTable = TableGatewayFactory::getDishPriceTable();
            $unitTable = TableGatewayFactory::getUnitTable($this->getLang());
            if($priceArr)
                foreach ($priceArr as $aPrice) {
                    $unitItem = $unitTable->getUnitByName($aPrice['unit']);
                    $unitIdStr = $unitItem?$unitItem->id:null;
                    $dishPriceTable->insert(array('dish_id'=>$dishId, 'price'=>str_replace(array('.',','), '', $aPrice['price']),
                        'currency_unit'=>$aPrice['currency_unit'], 'unit_id'=>$unitIdStr));
                }

            $dishArticleTable = TableGatewayFactory::getDishArticleTable($this->getLang());
            if($articleArr)
                foreach ($articleArr as $anArticle) {
                    $dishArticleTable->insert(array('lang'=>$dishArticleTable->getLang(),
                        'title'=>$anArticle['title'],'url'=>$anArticle['url'], 'dish_id'=>$dishId));
                }


            $dishImageTable = TableGatewayFactory::getDishImageTable();
            if($allImages)
                foreach ($allImages as $anImage) {
                    $dishImageTable->insert(array('dish_id'=>$dishId, 'path'=>$anImage));
                }

    }

    public function updateDish($paramArr, $id){

        $name = $paramArr['name'];
        $description = $paramArr['description'];
        $active = $paramArr['active'];
        $allTag = $paramArr['allTag'];
        $content = $paramArr['content'];
        $ingredient = $paramArr['ingredient'];
        $howTo = $paramArr['howTo'];
        $mainCategories = $paramArr['mainCategories'];
        $subCategories = $paramArr['subCategories'];
        $priceArr = $paramArr['priceArr'];
        $properties = $paramArr['properties'];
        $articleArr = $paramArr['articleArr'];
        $allImages = $paramArr['allImages'];


        if(strlen($name) == 0)
            throw new BusinessException('Chưa nhập tên');
        if(strlen($description) == 0)
            throw new BusinessException('Chưa nhập mô tả');

        $propertiesAsString =  '';
        if( count($properties) > 0)
            $propertiesAsString = implode(Constant::$SYSTEM_DELIMINATOR, $properties);

        $this->update(array('property' => $propertiesAsString, 'active'=>$active), $id);

        $dishItem = $this->getDish($id);
        $dishLangItem = $dishItem->getDishLang($this->getLang());
        $dishLangTable = TableGatewayFactory::getDishLangTable($this->getLang());
        $dishLangTable->update(array('dish_id'=>$id, 'content'=>$content,
            'how_to'=>$howTo, 'ingredient'=>$ingredient, 'name'=>$name,
            'alias'=>CommonHelper::vietnameseToASCII($name),
            'description'=>$description), $dishLangItem->id);

        $dishItem->detachCategories($this->getLang());

        $dishCategoryTable = TableGatewayFactory::getDishCategoryTable();
        if($mainCategories)
            foreach ($mainCategories as $aCategory) {
                    $dishCategoryTable->insert(array('dish_id'=>$id,
                        'category_id'=>$aCategory));
            }
        if($subCategories)
            foreach ($subCategories as $aCategory) {
                    $dishCategoryTable->insert(array('dish_id'=>$id,
                        'category_id'=>$aCategory));
            }

        $dishItem->detachTags($this->getLang());
        $dishTagTable = TableGatewayFactory::getDishTagTable($this->getLang());
        if($allTag)
            foreach ($allTag as $aTag) {
                $dishTagTable->insert(array('dish_id'=>$id, 'tag'=>$aTag));
            }

//        throw new BusinessException('mama calls me');
        $dishItem->detachPrices();
        $dishPriceTable = TableGatewayFactory::getDishPriceTable();
        $unitTable = TableGatewayFactory::getUnitTable($this->getLang());
        if($priceArr)
            foreach ($priceArr as $aPrice) {
                $unitItem = $unitTable->getUnitByName($aPrice['unit']);
                $unitIdStr = $unitItem?$unitItem->id:null;
                $dishPriceTable->insert(array('dish_id'=>$id, 'price'=>str_replace('.', '', $aPrice['price']),
                    'currency_unit'=>$aPrice['currency_unit'], 'unit_id'=>$unitIdStr));
            }

        $dishItem->detachArticles($this->getLang());
        $dishArticleTable = TableGatewayFactory::getDishArticleTable($this->getLang());
        if($articleArr)
            foreach ($articleArr as $anArticle) {
                $dishArticleTable->insert(array('lang'=>$dishArticleTable->getLang(),
                    'title'=>$anArticle['title'],'url'=>$anArticle['url'], 'dish_id'=>$id));
            }

        $dishItem->detachImages();
        $dishImageTable = TableGatewayFactory::getDishImageTable();
        if($allImages)
            foreach ($allImages as $anImage) {
                $dishImageTable->insert(array('dish_id'=>$id, 'path'=>$anImage));
            }
    }



}